<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8">
	<title>直播排班</title>
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<meta name="apple-mobile-web-app-status-bar-style" content="black">
	<meta name="apple-mobile-web-app-capable" content="yes">
	<meta name="format-detection" content="telephone=no">
	<link href="/node_modules/LobsterUIFrame/layuiadmin/layui/css/layui.css" rel="stylesheet" />
	<link href="/node_modules/LobsterUIFrame/layuiadmin/style/admin.css" rel="stylesheet" />
	<link href="/node_modules/LobsterUIFrame/layuiadmin/layui/css/modules/layui-icon-extend/iconfont.css"
		rel="stylesheet" />
	<script src="/node_modules/LobsterUIFrame/layuiadmin/layui/layui.js"></script>
	<style>
		.page-head {
			display: flex;
			margin-bottom: 10px;
		}

		table {
			border-collapse: collapse;
		}

		td {
			height: 40px;
			width: 15vw;
		}

		th {
			height: 40px;
			width: 15vw;
		}

		table,
		th,
		td {
			border: 1px solid #EAEAEA;
			background-color: #FFF;
			text-align: center;
		}
	</style>
</head>

<body>
	<div class="layui-fluid">
		<div class="layui-card">
			<div class="layui-form layui-card-header layuiadmin-card-header-auto">
				<div class="layui-input-inline">
					<label class="layui-form-label">课程名称：</label>
					<div class="layui-input-inline">
						<input type="text" name="CourseName" id="CourseName" placeholder="请输入名称查询" autocomplete="off"
							class="layui-input">
					</div>
				</div>
				<div class="layui-input-inline">
					<label class="layui-form-label">课程类型：</label>
					<div class="layui-input-inline">
						<select name="CategoryId" id="CategoryId" lay-filter="CategoryId">
							<option value="-1" selected="selected">全部</option>
						</select>
					</div>
				</div>
				<div class="layui-input-inline">
					<label class="layui-form-label">医生姓名：</label>
					<div class="layui-input-inline">
						<input type="text" name="AnchorName" id="AnchorName" placeholder="请输入姓名查询" autocomplete="off"
							class="layui-input">
					</div>
				</div>
				<div class="layui-input-inline">
					<button class="layui-btn layuiadmin-btn-useradmin" lay-submit lay-filter="LAY-app-front-search"
						id="btnSearch">
						<i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>查询
					</button>
					<button class="layui-btn layuiadmin-btn-useradmin" lay-submit lay-filter="copyschedule"
						id="copyschedule">
						<i class="layuiadmin-button-btn"></i>复制排班
					</button>
				</div>
			</div>

			<div class="layui-card-body">
				<div class="page-head">
					<div id="patient" style="flex:1"></div>
					<div style="width:300px;display:flex;align-items:flex-end;justify-content:flex-end">
						<button style="margin-right:10px;" class="layui-btn" type="button" lay-filter="btnTopWeek"
							id="btnTopWeek">上一周</button>
						<button style="margin-right:10px;" class="layui-btn layui-btn-normal" type="button"
							lay-filter="btnCurWeek" id="btnCurWeek">本周</button>
						<button style="margin-right:10px;" class="layui-btn" type="button" lay-filter="btnNextWeek"
							id="btnNextWeek">下一周</button>
					</div>
				</div>
				<table id="dataTable" lay-filter="dataTable"></table>
			</div>
		</div>
	</div>


	<script type="text/html" id="flagTpl">
		    {{#  if(d.DelFlag == '1'){ }}
		    <span style="color:red;">停用</span>
		    {{#  } else { }}
		    启用
		    {{#  } }}
	</script>
</body>

</html>

<script>
	layui.config({
		base: '/node_modules/LobsterUIFrame/layuiadmin/' //静态资源所在路径
	}).extend({
		index: 'lib/index' //主入口模块
	});

	layui.define(['index', 'layer', 'form', 'element', 'table', 'tree'], function () {
		var layer = layui.layer;
		var form = layui.form;
		var element = layui.element;
		var table = layui.table;
		var $ = layui.$;
		var admin = layui.admin;
		var setter = layui.setter;
		var tree = layui.tree;


		var controller = {
			data: {
				datatable: null,
				layerindex: 0,
				model: {},
				currentFirstDate: 0,
				dateArr: [],//日期
				scheduledata: {},
			},
			//初始化页面
			initpage: function () {
				var self = this
				this.initevent(function () {
					self.initDate(0);
					self.initTable();
				});

			},
			getbaseurl: function (fun) {
				var url = "/lowcode/APP20210908194005415/live/?view=layui&fun=" + fun;
				return url;
			},
			//打开弹层
			openlayer: function (title, elem, successfunction, yesfunction, width, height) {
				var self = this;
				layer.open({
					type: 2
					, title: title
					, content: elem
					, maxmin: true
					, area: [width, height]  //宽，高
					, btn: ['保存', '取消']
					, success: function (layero, index) {
						if (successfunction) {
							successfunction();
						}
					}
					, btn2: function (index, layero) {
						$("#LAY-app-form-reset").trigger('click');
					}
					, cancel: function () {
						$("#LAY-app-form-reset").trigger('click');
					}
					, yes: function (index, layero) {
						self.data.layerindex = index;
						console.log(178)
						getResult((field) => {
							console.log(field)
							if (field != null) {
								layer.msg('正在处理，请稍候', { icon: 16, time: 0, shade: [0.3, '#393D49'] });
								if (yesfunction) {
									yesfunction(field);
								}
							}
						})

					}
				});
			},
			//关闭弹层
			closelayer: function () {
				layer.close(this.data.layerindex);
			},
			//初始化事件
			initevent: function (func) {
				var self = this;
				self.initselect();
				var url = this.getbaseurl("LiveCourse.getbaseinfo");
				admin.req({
					url: url,  //控制器名称，方法名称
					data: {},
					done: function (res) {
						self.data.baseinfo = res.data;
						if (func) {
							func();
						}
					}
				});
				//查找reload,通过条件，查询网格的table重载数据显示到界面
				form.on("submit(LAY-app-front-search)", function (data) {
					self.initTable()
				});

				form.on("submit(copyschedule)", function (data) {
					console.log('copyschedule')
					self.openlayer('复制排班', 'liveschedulecopy.html', null, function (field) { self.saveschedulecopy(field) }, '50%', '100%')
					return false
				});

				$('#btnTopWeek').click(function () {
					self.initDate(-7);
					self.ButtonColor($(this));
					self.initTable()
				});
				//监听本周日期事件
				$('#btnCurWeek').click(function () {
					self.data.currentFirstDate = 0
					self.initDate(0);
					self.ButtonColor($(this));
					self.initTable()
				});
				//监听下一周日期事件
				$('#btnNextWeek').click(function () {
					self.initDate(7);
					self.ButtonColor($(this));
					self.initTable()
				});

				$("body").on('click', ".tdItem", function (e) {
					e.stopPropagation();
					console.log(e.currentTarget.dataset)
					var date = e.currentTarget.dataset.date;
					var courseid = e.currentTarget.dataset.courseid;
					var empid = e.currentTarget.dataset.empid;
					var roomid = e.currentTarget.dataset.roomid;
					var DocName = e.currentTarget.dataset.docname;
					var scheduleid = e.currentTarget.dataset.scheduleid;
					var model = { date, courseid, empid, roomid, DocName, scheduleid }
					console.log(model)
					if (date == "" || empid == "null") {
						return
					}
					window.mod = model
					self.openlayer('直播时段', 'livescheduledetail.html', null, function (field) { self.savescheduledetail(field) }, '50%', '100%')
				})
			},
			initselect: function () {
				var self = this;
				var url = self.getbaseurl("LiveCourse.getcoursecategory");
				admin.req({
					type: 'get',
					url: url,
					done: function (obj) {
						$.each(obj.data.data, function (index, item) {
							$("#CategoryId").append(new Option(item.CategoryName, item.CategoryId))
						})
						layui.form.render("select")
					}
				});
			},
			ButtonColor(_this) {
				_this.parent("div").find("[type='button']").removeClass("layui-btn-normal");
				_this.addClass("layui-btn-normal");
			},
			//初始化日期
			initDate(n) {
				var self = this;
				self.data.dateArr = [];
				var date = new Date();
				self.data.currentFirstDate = self.data.currentFirstDate + n;
				date.setDate(date.getDate() + self.data.currentFirstDate);
				var monday = self.getMonday(date)
				self.data.dateArr.splice(0, 0, "");
				self.data.dateArr.splice(0, 0, "");
				self.addDate(monday, -1)
				for (var i = 0; i < 7; i++) {
					self.data.dateArr.push(self.formatDate(self.addDate(monday, 1)))
				}

				console.log(self.data.dateArr);
			},
			getMonday: function (date) {
				var day = date.getDay();
				var deltaDay;
				if (day == 0) {
					deltaDay = 6;
				} else {
					deltaDay = day - 1;
				}
				var monday = new Date(date.getTime() - deltaDay * 24 * 60 * 60 * 1000);
				monday.setHours(0);
				monday.setMinutes(0);
				monday.setSeconds(0);
				return monday;  //返回本周的周一的0时0分0秒
			},
			addZero(num) {
				if (num < 10) {
					return '0' + num;
				}
				return num;
			},
			formatDate(date) {
				var year = date.getFullYear() + '-';
				var month = (date.getMonth() + 1);
				if (month < 10)
					month = "0" + month
				month = month + '-';
				var day = date.getDate();
				if (day < 10)
					day = "0" + day;
				return year + month + day
			},
			addDate(date, n) {
				date.setDate(date.getDate() + n);
				return date;
			},
			//初始化表头
			initTable() {
				var self = this;
				self.getData().then(res => {
					console.log(res)
					self.data.scheduledata = res.data
					self.createTableTitle();
				});
			},
			createTableTitle() {
				var self = this;
				$('#dataTable').empty();
				var table = document.querySelector('#dataTable');
				var trHead = document.createElement("tr");
				table.appendChild(trHead);
				for (var k = 0; k < self.data.dateArr.length; k++) {
					var td = document.createElement("th");
					trHead.appendChild(td);
					if (k == 0) {
						td.innerHTML = "课程";
					}
					else if (k == 1) {
						td.innerHTML = "医生";
					}
					else {
						td.innerHTML = self.data.dateArr[k].substr(5, 5);
					}
				}
				self.createData();
				self.mergeCell("dataTable", 1, 0, 0);

			},
			createData: function () {
				var self = this;
				var table = document.querySelector('#dataTable');
				var courses = self.data.scheduledata.Course
				var schedules = self.data.scheduledata.Schedule
				courses.forEach(x => {
					var trHead = document.createElement("tr");
					table.appendChild(trHead);
					for (var k = 0; k < self.data.dateArr.length; k++) {
						var date = self.data.dateArr[k]
						var td = document.createElement("td");
						td.setAttribute("class", "tdItem");
						td.setAttribute("data-date", date);
						td.setAttribute("data-CourseId", x.CourseId);
						td.setAttribute("data-EmpId", x.EmpId);
						td.setAttribute("data-RoomId", x.RoomId);
						td.setAttribute("data-DocName", x.DocName);
						trHead.appendChild(td);
						if (k == 0) {
							td.innerHTML = x.CourseName;
						}
						else if (k == 1) {
							td.innerHTML = x.DocName;
						}
						else {
							var scarr = schedules.filter(y => y.RoomId == x.RoomId && y.ScheduleDate.substr(0, 10) == date)
							if (scarr && scarr.length > 0) {
								console.log(scarr)
								var str = ""
								scarr.forEach(e => {
									str += '<div>' + e.StartTime + '~' + e.EndTime + '</div>'
								});

								td.setAttribute("data-ScheduleId", scarr[0].ScheduleId);
								td.innerHTML = str
							} else {
								//td.innerHTML = '<div class="tdItem" data-date="' + date + '" data-CourseId="' + x.CourseId + '" data-EmpId="' + x.EmpId + '">未排班</div>'
							}
						}
					}
				});
			},
			mergeCell(table, startRow, endRow, col) {
				var self = this;
				var tb = document.getElementById(table);
				if (!tb || !tb.rows || tb.rows.length <= 0) {
					return;
				}
				if (col >= tb.rows[0].cells.length || (startRow >= endRow && endRow != 0)) {
					return;
				}
				if (endRow == 0) {
					endRow = tb.rows.length - 1;
				}
				for (var i = startRow; i < endRow; i++) {
					//如果相等就合并单元格,合并之后跳过下一行
					if (tb.rows[startRow].cells[col].innerHTML == tb.rows[i + 1].cells[col].innerHTML) {
						//tb.rows[i + 1].removeChild(tb.rows[i + 1].cells[6]);		// 合并第6列
						//tb.rows[i + 1].removeChild(tb.rows[i + 1].cells[5]);		// 合并第5列
						//tb.rows[i + 1].removeChild(tb.rows[i + 1].cells[4]);		// 合并第4列
						//tb.rows[i + 1].removeChild(tb.rows[i + 1].cells[3]);		// 合并第3列
						tb.rows[i + 1].removeChild(tb.rows[i + 1].cells[col]);		// 合并第1列
						//tb.rows[startRow].cells[6].rowSpan = (tb.rows[startRow].cells[6].rowSpan) + 1;
						//tb.rows[startRow].cells[5].rowSpan = (tb.rows[startRow].cells[5].rowSpan) + 1;
						//tb.rows[startRow].cells[4].rowSpan = (tb.rows[startRow].cells[4].rowSpan) + 1;
						//tb.rows[startRow].cells[3].rowSpan = (tb.rows[startRow].cells[3].rowSpan) + 1;
						tb.rows[startRow].cells[col].rowSpan = (tb.rows[startRow].cells[col].rowSpan) + 1;
					} else {
						self.mergeCell(table, i + 1, endRow, col);
						break;
					}
				}
			},


			getData() {
				var self = this;
				return new Promise((resolve, reject) => {
					admin.req({
						url: this.getbaseurl("LiveCourse.getschedule"),
						data: {
							CourseName: $("#CourseName").val(),
							CategoryId: $("#CategoryId").val(),
							DocName: $("#AnchorName").val(),
							startdate: self.data.dateArr[2],
							enddate: self.data.dateArr[8]
						},
						method: "GET",
						done: res => {
							resolve(res);
						}
					})
				})
			},
			//保存排班
			savescheduledetail: function (field) {
				var self = this;
				var url = self.data.baseinfo.apiGateway + "/live/v1/Live/SaveRoom";



				admin.req({
					type: 'post',
					url: url,
					contentType: 'application/json',
					data: JSON.stringify({
						ScheduleId: window.mod.scheduleid || 0,
						CourseId: window.mod.courseid,
						EmpId: window.mod.empid,
						DocName: window.mod.DocName,
						workId: self.data.baseinfo.WorkId,
						ScheduleDate: window.mod.date,
						roomTimes: field
					}),
					done: function (obj) {
						layer.msg("保存成功");

						self.initTable();
						self.closelayer(); //关闭弹层
					}
				});
			},
			saveschedulecopy: function (field) {
				var self = this;
				var url = self.data.baseinfo.LiveapiGateway + "/live/v1/Live/ScheduleCopy";



				admin.req({
					type: 'post',
					url: url,
					contentType: 'application/json',
					data: JSON.stringify(field),
					done: function (obj) {
						layer.msg("保存成功");

						self.initTable();
						self.closelayer(); //关闭弹层
					}
				});
			},
		}

		/*
		* 入口
		*/
		controller.initpage();
	});

</script>